import pandas as pd
import matplotlib.pyplot as plt

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 导入数据
data = pd.read_excel('第二章 图表(前15).xlsx', sheet_name='8 数值百分比', usecols='B:F', skiprows=1)

# 创建图形和轴
fig, ax = plt.subplots(figsize=(10, 6))

# 设置条形图的宽度
bar_width = 0.4
index = range(len(data))

bars1 = ax.barh(index, data['销量'], bar_width, color='skyblue', label='销量')
bars2 = ax.barh(index, 500, bar_width, color='lightgreen', label='同比去年', left=max(data['销量']))

# 添加标题和标签
ax.set_title('2021年各区域销量及同比情况')

# 设置Y轴标签
ax.set_yticks(index)
ax.set_yticklabels(data['区域'])

# 隐藏边框
for spine in ax.spines.values():
    spine.set_visible(False)

# 隐藏X轴
ax.xaxis.set_visible(False)

for i, bar in enumerate(bars1):
    ax.text(bar.get_width(), bar.get_y() + bar.get_height() / 2, f"{data['销量'][i]}", va='center', ha='right', color='black')

for i, bar in enumerate(bars2):
    ax.text(max(data['销量']) + bar.get_width(), bar.get_y() + bar.get_height() / 2, f"{data['同比去年'][i] * 100:.1f}%", va='center', ha='right', color='black')

# 导出图片
#plt.savefig('D:/python charm/01/可视化/第二章/图片/数值百分比图.png', dpi=300, bbox_inches='tight')

# 显示图形
plt.show()